/*
 * Copyright (c) 2025 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#include <cinttypes>

#include <iservice_registry.h>
#include <if_system_ability_manager.h>
#include <system_ability_definition.h>

#include <smart_serve_log.h>
#include <smart_serve_client.h>
#include <ismart_serve_service.h>

namespace OHOS {
namespace SmartServe {

SmartServeClient& SmartServeClient::GetInstance()
{
    static SmartServeClient instance;
    return instance;
}

bool SmartServeClient::TryConnect()
{
    std::lock_guard<std::mutex> lock(mutex_);
    if (remoteObject_) {
        return true;
    }

    sptr<ISystemAbilityManager> systemManager = SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager();
    if (!systemManager) {
        SMART_SERVE_LOGE("SmartServeClient::Fail to get registry.");
        return false;
    }

    remoteObject_ = systemManager->GetSystemAbility(SMART_SERVE_SERVICE_ID);
    if (!remoteObject_) {
        SMART_SERVE_LOGE("SmartServeClient::Fail to connect smart server service.");
        return false;
    }

    recipient_ = new SmartServeDeathRecipient(*this);
    remoteObject_->AddDeathRecipient(recipient_);
    SMART_SERVE_LOGI("SmartServeClient::Connect smart server service success.");
    return true;
}

std::string SmartServeClient::Serve(const std::string& request)
{
    SMART_SERVE_LOGI("SmartServeClient ::Serve.");
    if (TryConnect() != true) {
        SMART_SERVE_LOGE("Connnect smart server service failed");
        return "";
    }
    sptr<ISmartServeService> smartServe = iface_cast<ISmartServeService>(remoteObject_);
    std::string response = "";
    smartServe->Serve(request, response);
    return response;
}

void SmartServeClient::StopRemoteObject()
{
    if (remoteObject_) {
        remoteObject_->RemoveDeathRecipient(recipient_);
    }
    remoteObject_ = nullptr;
}

void SmartServeClient::SmartServeDeathRecipient::OnRemoteDied(const wptr<IRemoteObject> &remote)
{
    smartServeClient_.StopRemoteObject();
}

} // namespace SmartServe
} // namespace OHOS